#!/bin/bash
#定义帮助函数
#检查运行环境，JDK,MAVEN
#定义获取NULS2.0运行环境函数
#定义获取模板函数
#定义打包函数

cd `dirname $0`
ROOT_PATH=`pwd`
NULS2_REPO="https://github.com/nuls-io/nuls-v2.git"
NULS2_BRANCH="chain-box-used"
NULS2_RUNTIME_DIR="NULS_WALLET_RUNTIME"
NULS2_REPO_DIR=".NULS2.0"
# NULS2_REPO_DIR="../nerve-network"
WALLET_NAME="NULS_WALLET"
CONF=$ROOT_PATH/conf
NULS_WALLET_PATH="${ROOT_PATH}/${WALLET_NAME}"
JAVA_MODULE_TEMP_REPO="https://github.com/nuls-io/nuls-module-template-java.git"
PACKAGE_JRE=
TEMPLATLIST="java"
TARGET_OS=linux
if [ -z "$PACKAGE_ENV" ]; then
    PACKAGE_ENV=prod
fi    

help()
{
    cat <<- EOF
    Desc: NULS-engine 脚本程序
    Usage: ./tools
            -B 打包bata版本
            -t <language> [folder name] 获取指定开发语言的模块程序模块 
                <language> 开发语言 ，如java
                [folder name] 下载到指定名字的目录下
            -r <folder name> 重新获取业务模块代码，并执行package进行编译     
            -l 查看支持的模板列表    
            -p [业务模块目录...] 构建NULS2.0钱包，此参数必须放在会后面
            -a 添加一个基础模块
            -d 移除一个基础模块
            -s 查看配置的待打包的基础模块列表   
            -i <package.ncf>指定需要打包的基础模块的配置文件    
            -o <folder path> 指定输出目录     
            -z -p打包时是否输出tar.gz压缩包
            -J <jre path> 将jdk集成进程序包中
            -b 指定nuls-v2分支
            -O 指定打包的系统版本可用枚举：window,linux,maos,默认linux
            -h 查看帮助
            
EOF
    exit 0
}

getModuleItem(){
    while read line
    do
        pname=`echo $line | awk -F '=' '{print $1}'`
        pvalue=`awk -v a="$line" '
                        BEGIN{
                            len = split(a,ary,"=")
                            r=""
                            for ( i = 2; i <= len; i++ ){
                                if(r != ""){
                                    r = (r"=")
                                }
                                r=(r""ary[i])
                            }
                            print r
                        }
                    '`        
        if [ "${pname}" == $2 ]; then
            echo ${pvalue};
            return 1;
        fi
    done < $1
    return 0
}


#日志打印函数
echoRed() { echo $'\e[0;31m'$1$'\e[0m'; } #print red
echoGreen() { echo $'\e[0;32m'$1$'\e[0m'; } #print green
echoYellow() { echo $'\e[0;33m'$1$'\e[0m'; } #print yellow
log(){ #print date prefix and green
    now=`date "+%Y-%m-%d %H:%M:%S"`
    echoGreen "$now $@"
}

# 检查java版本 must be 11
checkJavaVersion(){
    JAVA="$JAVA_HOME/bin/java"
    if [ ! -r "$JAVA" ]; then
        JAVA='java'
    fi

    JAVA_EXIST=`${JAVA} -version 2>&1 |grep 11`
    if [ ! -n "$JAVA_EXIST" ]; then
            log "JDK version is not 11"
            ${JAVA} -version
            exit 0
    fi
}

checkMaven(){
    MAVEN_EXIST=`${MVN} -version 2>&1 |grep "Apache Maven"`
    if [ ! -n "$MAVEN_EXIST" ]; then
            log "maven not install"
            exit 0
    fi
}

checkJDKAndMaven(){
    checkJavaVersion
    # checkMaven
}

checkJDKAndMaven
WGET_EXIST=`wget -V 2>&1 |grep "GNU Wget"`
if [ -z "$WGET_EXIST" ]; then
    echoRed "not found wget , install wget "
    exit 0;
fi

PACKAGE_CONFIG="`pwd`/.package.ncf"

#编辑.package.ncf
updatePackage(){
    if [ ! -f "${PACKAGE_CONFIG}" ]; then
        if [ ! -d "$NULS2_REPO_DIR" ]; 
        then
            git clone $NULS2_REPO $NULS2_REPO_DIR
            cd $NULS2_REPO_DIR
            git checkout $NULS2_BRANCH
            cd ..
        fi
        cp "${NULS2_REPO_DIR}/build/package-base.ncf" ${PACKAGE_CONFIG}
        #statements
    fi 
    c="sed -n '/^$1/p' $PACKAGE_CONFIG"
    has=`eval $c`;
    if [ -n "$has" ];
    then
        os=`uname`
        if [ "$os" == "Darwin" ];
        then
            eval "sed -i '' 's/^$has/$1=$2/' $PACKAGE_CONFIG"
        else
            eval "sed -i 's/^$has/$1=$2/' $PACKAGE_CONFIG"
        fi
    else
        if [ $2 == "1" ]; then
            echo "${1}=1" >> $PACKAGE_CONFIG
            echo "" >> $PACKAGE_CONFIG
        fi
    fi
    # exit 0
}

showPackageModule(){
    log "=========================="
    log "package module list"
    while read line
    do
        TEMP=`echo $line|grep -Eo '\[.+\]'`
        if [ -z "$TEMP" ]; then
            isPackage=`echo $line |grep "=1"`
            if [ -n "$isPackage" ]; then
                log "---->$line" | awk -F '=' '{print $1}'
            fi
        fi
    done < $PACKAGE_CONFIG
    log "=========================="
}

showTemplateList(){
    while read line
    do
        
        TEMP=`echo $line|grep -Eo '\[.+\]'`
        if [ -z "$TEMP" ]; then
            pname=`echo $line | awk -F '=' '{print $1}'`
            echo $pname
            gitUrl=`getModuleItem "${ROOT_PATH}/template" ${pname}`
            # curl "${gitUrl}/.describe"
            # isPackage=`echo $line |grep "=1"`
            # if [ -n "$isPackage" ]; then
            #     log "---->$line" | awk -F '=' '{print $1}'
            #fi
        fi
        
    done < "${ROOT_PATH}/template"
}

#检查是否已经clone了nuls2.0
initAndUpdateNulsRuntime()
{

    MAVEN_EXIST=`mvn -version 2>&1 |grep "Apache Maven"`
    # echo $MAVEN_EXIST
    if [ -z "$MAVEN_EXIST" ]; then
        if [ ! -d "./lib" ]; then
            mkdir ./lib
        fi    
        if [ ! -d "./lib/maven" ]; then
            cd ./lib
            WGET_EXIST=`wget -V 2>&1 |grep "GNU Wget"`
            if [ -z "$WGET_EXIST" ]; then
                echoRed "not found wget , install wget "
                exit 0;
            fi
            wget http://mirrors.tuna.tsinghua.edu.cn/apache/maven/maven-3/3.6.1/binaries/apache-maven-3.6.1-bin.tar.gz
            tar -xvf ./apache-maven-3.6.1-bin.tar.gz
            mv ./apache-maven-3.6.1 ./maven
            cd ..
        fi
        path=`pwd`
        export MAVEN_HOME=${path}/lib/maven
        export PATH=${PATH}:${MAVEN_HOME}/bin
    fi
    if [ ! -d "$NULS2_REPO_DIR" ]; 
    then
        git clone $NULS2_REPO $NULS2_REPO_DIR
        cd $NULS2_REPO_DIR
        git checkout $NULS2_BRANCH
    else
        cd $NULS2_REPO_DIR
        git pull  
        git checkout $NULS2_BRANCH
    fi
    if [ ! -f "${PACKAGE_CONFIG}" ]; then
        cp "./build/package-base.ncf" ${PACKAGE_CONFIG}
        #statements
    fi
    len=$#
    for ((i=2;i<=$len;i++));do
        module=`eval echo '$'"$i"`
        # echo $module
        updatePackage $module 1
    done
    cp ${PACKAGE_CONFIG} ./.package.ncf
    echo "../$1"
    ./package -a "mykernel"
    #echo "./package -N -o $1 ${PACKAGE_JRE}"
    ./package ${IS_BETA} -N -o "$1" ${PACKAGE_JRE} -O $TARGET_OS
    cp $CONF/nuls.ncf $1
    cp $CONF/genesis-block.json $1
    cd ..
    # rm -rf $NULS2_REPO_DIR
}

getModuleTemplate(){
    templateName=$1
    dirName=$2
    if [ -z "$dirName" ]; then
        dirName="$1"
    fi
    gitUrl=`getModuleItem ./template $templateName`
    if [ -z "$gitUrl" ]; then
        #statements 
        echo "not found template : $templateName"
        echo "template list : ${TEMPLATLIST}"
        exit 0
    fi
    echo $gitUrl
    git clone $gitUrl $dirName
    cd $dirName
    if [ -x ./init.sh ]; then 
        ./init.sh $dirName
        rm -f ./init.sh
    fi
    cat README.md
    #rm -rf .git

}

updateTemplate(){
    module=$1
    if [ ! -d "${module}" ]; then
        echo "not found module folder"
        exit 0
    fi
    baseModules=
    if [ ! -f "${PACKAGE_CONFIG}" ]; 
    then
        echoYellow "not found ${PACKAGE_CONFIG}, don't know basis module list"
    else
       while read line
       do
            TEMP=`echo $line|grep -Eo '\[.+\]'`
            if [ -z "$TEMP" ]; then
                isPackage=`echo $line |grep "=1"`
                if [ -n "$isPackage" ]; then
                    if [ -n "$baseModules" ]; then
                        baseModules="${baseModules},"
                    fi
                    baseModules="${baseModules}$(echo ${line} | awk -F '=' '{print $1}')"
                fi
            fi
        done < $PACKAGE_CONFIG     
    fi
    cd $module
    git pull
    ./package $PACKAGE_ENV
}

packageOutModule(){
    module=$1

    echo $module
    if [ ! -d $module ]; then
        return ;
    fi
    cd $module;
    if [ -n "`ls |grep module.ncf`" ]; 
    then 
        if [ ! -d "outer" ]; then
            if [ -f "./package" ]; then                
                ./package $PACKAGE_ENV
            fi
            if [ ! -d "outer" ]; then
               echo "not found outer folder"
               exit 0
            fi
                    
        fi
        if [ ! -f "outer/Module.ncf" ]; then
            echo "not found Module.ncf"
            exit 0
        fi
        echo "packing ${module}"
        moduleName=`getModuleItem  "outer/Module.ncf" "APP_NAME"`;
        version=`getModuleItem  "outer/Module.ncf" "VERSION"`;
        if [ -z "$moduleName" ]; then
            echo "must setting APP_NAME"
            exit 0
        fi
        if [ -z "$version" ]; then
            echo "must setting VERSION"
            exit 0
        fi
        
        if [ ! -d "${outPath}/Modules/Nuls/$moduleName" ]; then
            mkdir "${outPath}/Modules/Nuls/$moduleName"
        fi
        if [ -d "${outPath}/Modules/Nuls/$moduleName/$version" ]; then
            rm -rf "${outPath}/Modules/Nuls/$moduleName/$version"
        fi
        mkdir "${outPath}/Modules/Nuls/$moduleName/$version"
        cp -r ${module}/outer/* "${outPath}/Modules/Nuls/$moduleName/$version"
        echo "copy ${module}/outer/ to ${outPath}/Modules/Nuls/$moduleName/$version"
        # echo $moduleName
        echo $moduleName >> ${outPath}/.modules
        echo "package ${module} finish"
    else
        for f in `ls`
        do
            if [ -d $f ]; then
                packageOutModule "`pwd`/${f}"
            fi  
        done
    fi    
    cd ..
    
}

packageToNuls(){
    outPath=${NULS_WALLET_PATH}
    log "NULS_WALLET PATH : ${NULS_WALLET_PATH}"
    if [ -d "$outPath/Modules/Nuls" ]; then
        rm -rf "$outPath/Modules/Nuls"
    fi
    initAndUpdateNulsRuntime $outPath
    baseModules=
    while read line
    do
        if [ -n "$baseModules" ]; then
                baseModules="${baseModules},"
        fi
        baseModules="${baseModules}${line}"
    done < "$outPath/.modules"
    echo $baseModules

    for module in $@
    do
        cd $ROOT_PATH
        # module=$1
        echo $module
        if [ ! -d $module ]; then
            echo "wrong module folder"
            exit 0;
        fi
        packageOutModule "`pwd`/$module"
    done

    cd $ROOT_PATH
    if [ -n "${BUILD_TAR}" ]; then
            log "============ BUILD ${WALLET_NAME}.tar.gz ==================="
            tar -zcPf "${WALLET_NAME}.tar.gz" ./${WALLET_NAME}
            log "============ BUILD ${WALLET_NAME}.tar.gz FINISH==================="
    fi
}


while getopts b:J:i:t:ha:r:sld:o:zpO:B name
do
            case $name in
            B)     IS_BETA=" -B "
                   ;;    
            O)
                   TARGET_OS=$OPTARG
                   ;;    
            b)
                   NULS2_BRANCH=$OPTARG
                   ;;    
            i)
                   if [ ! -f "$OPTARG" ]; then
                       echo "-i param error , must be file path"
                       exit 0 
                   fi
                   cp $OPTARG ./.package.ncf
                   ;;
            o)
                   if [ ! -d "$OPTARG" ]; then
                       #statements
                       mkdir "$OPTARG"
                   fi
                   NULS_WALLET_PATH=$OPTARG
                   ;;
            J)     PACKAGE_JRE=" -J `cd $OPTARG; pwd`"
                   ;;       
            z)
                   BUILD_TAR="1"    
                   ;;   
            p)     
                   modules=()
                   len=$#
                   # echo $OPTIND
                   for ((i=$OPTIND;i<=$len;i++));do
                       dir=`eval echo '$'"$i"`
                       modules[${#modules[@]}]=$dir
                   done    
                   #echo ${modules[@]/\//}
                   packageToNuls ${modules[@]%/}
                   exit
                   ;;
            t)     
                   dir=`eval echo '$'"$OPTIND"`
                   getModuleTemplate "$OPTARG" "$dir"
                   exit 0
                   ;;
            r)     updateTemplate "$OPTARG"    
                   exit 0 
                   ;;  
            # n)     modules=()
            #        len=$#
            #        for ((i=$OPTIND;i<=$len;i++));do
            #            dir=`eval echo '$'"$i"`
            #            modules[${#modules[@]}]=$dir
            #        done   
            #        initAndUpdateNulsRuntime $NULS2_RUNTIME_DIR ${modules[@]}
            #        exit 0
            #        ;;
            a)     updatePackage "$OPTARG" 1
                   exit 0
                   ;;
            d)     updatePackage "$OPTARG" 0
                   exit 0
                   ;;
            s)     showPackageModule
                   ;;
            l)     showTemplateList ;;       
            h)     help
                   exit 0
                   ;;
            ?)     exit 2;;
           esac
done




